// 注册页面组件

import React, { useState, useEffect } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { authApi } from '../api/auth';
import type { RegisterRequest } from '../types/auth';
import { useAuth } from '../contexts/AuthContext';
import { handleApiError, getErrorMessage } from '../utils/errorHandler';
import './RegisterPage.css';

/**
 * 注册页面组件
 * 提供用户注册功能
 */
const RegisterPage: React.FC = () => {
  const { isAuthenticated } = useAuth();
  const navigate = useNavigate();
  
  // 表单状态
  const [formData, setFormData] = useState<RegisterRequest>({
    username: '',
    email: '',
    password: '',
    confirmPassword: '',
    nickname: ''
  });
  
  // 加载状态
  const [loading, setLoading] = useState(false);
  
  // 错误信息
  const [error, setError] = useState('');
  
  // 显示密码状态
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);

  // 如果已登录，重定向到首页
  useEffect(() => {
    if (isAuthenticated) {
      navigate('/', { replace: true });
    }
  }, [isAuthenticated, navigate]);

  // 表单验证
  const validateForm = (): boolean => {
    if (!formData.username.trim()) {
      setError('请输入用户名');
      return false;
    }
    if (formData.username.length < 3) {
      setError('用户名至少3个字符');
      return false;
    }
    if (!formData.email.trim()) {
      setError('请输入邮箱');
      return false;
    }
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
      setError('请输入有效的邮箱地址');
      return false;
    }
    if (!formData.password.trim()) {
      setError('请输入密码');
      return false;
    }
    if (formData.password.length < 6) {
      setError('密码至少6个字符');
      return false;
    }
    if (formData.password !== formData.confirmPassword) {
      setError('两次输入的密码不一致');
      return false;
    }
    if (!formData.nickname.trim()) {
      setError('请输入昵称');
      return false;
    }
    return true;
  };

  // 处理表单提交
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!validateForm()) {
      return;
    }

    setLoading(true);
    setError('');

    try {
      const { confirmPassword, ...registerData } = formData;
      const response = await authApi.register(registerData);
      
      if (response.code === 0) {
        // 注册成功，跳转到登录页面
        navigate('/login', { replace: true });
      } else {
        setError(response.message || '注册失败');
      }
    } catch (err) {
      const errorMsg = getErrorMessage(err);
      setError(errorMsg);
      handleApiError(err);
    } finally {
      setLoading(false);
    }
  };

  // 处理输入变化
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData((prev: RegisterRequest) => ({ ...prev, [name]: value }));
    // 清除错误信息
    if (error) {
      setError('');
    }
  };

  return (
    <div className="register-page">
      <div className="register-container">
        <div className="register-header">
          <h1 className="register-title">注册账号</h1>
          <p className="register-subtitle">加入玄枢足球预测，开启专业预测之旅</p>
        </div>

        <form className="register-form" onSubmit={handleSubmit}>
          {/* 错误提示 */}
          {error && (
            <div className="error-message">
              {error}
            </div>
          )}

          {/* 用户名输入 */}
          <div className="form-group">
            <label htmlFor="username" className="form-label">用户名</label>
            <input
              type="text"
              id="username"
              name="username"
              className="form-input"
              placeholder="请输入用户名（至少3个字符）"
              value={formData.username}
              onChange={handleInputChange}
              disabled={loading}
              autoComplete="username"
            />
          </div>

          {/* 邮箱输入 */}
          <div className="form-group">
            <label htmlFor="email" className="form-label">邮箱</label>
            <input
              type="email"
              id="email"
              name="email"
              className="form-input"
              placeholder="请输入邮箱地址"
              value={formData.email}
              onChange={handleInputChange}
              disabled={loading}
              autoComplete="email"
            />
          </div>

          {/* 昵称输入 */}
          <div className="form-group">
            <label htmlFor="nickname" className="form-label">昵称</label>
            <input
              type="text"
              id="nickname"
              name="nickname"
              className="form-input"
              placeholder="请输入昵称"
              value={formData.nickname}
              onChange={handleInputChange}
              disabled={loading}
              autoComplete="nickname"
            />
          </div>

          {/* 密码输入 */}
          <div className="form-group">
            <label htmlFor="password" className="form-label">密码</label>
            <div className="password-input-wrapper">
              <input
                type={showPassword ? 'text' : 'password'}
                id="password"
                name="password"
                className="form-input"
                placeholder="请输入密码（至少6个字符）"
                value={formData.password}
                onChange={handleInputChange}
                disabled={loading}
                autoComplete="new-password"
              />
              <button
                type="button"
                className="password-toggle"
                onClick={() => setShowPassword(!showPassword)}
                disabled={loading}
              >
                {showPassword ? '隐藏' : '显示'}
              </button>
            </div>
          </div>

          {/* 确认密码输入 */}
          <div className="form-group">
            <label htmlFor="confirmPassword" className="form-label">确认密码</label>
            <div className="password-input-wrapper">
              <input
                type={showConfirmPassword ? 'text' : 'password'}
                id="confirmPassword"
                name="confirmPassword"
                className="form-input"
                placeholder="请再次输入密码"
                value={formData.confirmPassword}
                onChange={handleInputChange}
                disabled={loading}
                autoComplete="new-password"
              />
              <button
                type="button"
                className="password-toggle"
                onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                disabled={loading}
              >
                {showConfirmPassword ? '隐藏' : '显示'}
              </button>
            </div>
          </div>

          {/* 提交按钮 */}
          <button
            type="submit"
            className="register-button"
            disabled={loading}
          >
            {loading ? '注册中...' : '注册'}
          </button>
        </form>

        {/* 登录链接 */}
        <div className="register-footer">
          <p className="login-link">
            已有账号？
            <Link to="/login" className="link">
              立即登录
            </Link>
          </p>
        </div>
      </div>
    </div>
  );
};

export default RegisterPage;